<?php

/*
 * Copyright 2014 gg.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Wechat\Model;
require_once './Public/phpQuery.php';
/**
 * Description of WechatReturnMsgModel
 *
 * @author gg
 */
class WechatReturnMsgModel {
    
    /**
     * 更新菜单
     * @return boolean 是否成功
     */
    public function setUpCustomMenu(){
        S(array('type'=>C('DATA_CACHE_TYPE')));
        if (!S('wc_lastMenuTime')){
            $token = $this->getAccessToken();
            $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$token;
            $result = $this->curlSafePost($url, C('WECHAT_CUSTOMENU'));
            $resJson = json_decode($result);
//            print_r($resJson);
            if ($resJson->errcode==0){
                S('wc_lastMenuTime',time(),6000);
                return TRUE;
            }else{
                S('wc_lastMenuTime',NULL);
                return FALSE;
            }
        }else{
            return TRUE;
        }
        
    }
    
    /*
     * 下载内容，订阅号无效，弃用
     * @param type $mediaId
     * @param type $filename
     * @param type $ext
     */
//    public function curlFileGet($mediaId,$filename,$ext){
//        $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.  
//                $this->getAccessToken() .'&media_id='.$mediaId;
//        $fp = fopen(TEMP_PATH."/wechatfile/".$filename.$ext, "w");
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt( $ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//        curl_setopt($ch, CURLOPT_FILE, $fp);
//        $result = curl_exec($ch);
//        echo $result;
//    }

        /**
     * https post方法
     * @param type $url
     * @param type $postData
     * @return bool
     */
    private function curlSafePost($url,$postData){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt( $ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch) ;
        return $result;
    }

    /**
     * https GET 方法
     * @param type $url
     * @return type
     */
    private function curlSafeGet($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt( $ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch) ;
        return $result;
    }


    /**
     * 获取授权字符串
     * @return type accessToken
     */
    public function getAccessToken(){
        S(array('type'=>C('DATA_CACHE_TYPE')));
        if (!S('wc_token')){
           $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1b583e7ad9a5a2a1&secret=28a8d2f6cca07b9ee44aeeec82114b66";
           $result = $this->curlSafeGet($url);
           $resJson = json_decode($result);
           S('wc_token',$resJson->access_token,6000);
        }
        return S('wc_token');
    }
    
    /**
     * 输出文本消息
     * @param type $object 传入消息
     * @param type $content 回复的消息
     * @param type $flag 是否星标
     */
    public function returnText($object, $content,$micro = 0, $flag = 0){
        $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>"
                . "<FromUserName><![CDATA[%s]]></FromUserName>"
                . "<CreateTime>%s</CreateTime><MsgType>"
                . "<![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content>"
                . "</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, 
                $object->ToUserName, time(), $content,$flag);
        $test = new \Wechat\Model\TestModel();
        $test->create(array('value'=>"Text||".$resultStr."||".time()."||$micro"));
        $test->add();
        echo $resultStr;
    }
    
    /*
     * 返回图片消息,订阅号无效
     * @param type $object 传入消息
     * @param type $mediaId 媒体id
     */
//    public function returnPic($object,$mediaId){
//        $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>"
//                . "<FromUserName><![CDATA[%s]]></FromUserName>"
//                . "<CreateTime>%s</CreateTime>"
//                . "<MsgType><![CDATA[image]]></MsgType>"
//                . "<Image><MediaId><![CDATA[%s]]></MediaId></Image></xml>";
//        $resultStr = sprintf($textTpl, $object->FromUserName, 
//                $object->ToUserName,time(),$mediaId);
//        $test = new \Wechat\Model\TestModel();
//        $test->create(array('value'=>"Pic||".$resultStr));
//        $test->add();
//        echo $resultStr;
//    }
    
    /**
     * 回复图文消息
     * @param type $object 传入消息
     * @param type $title 标题
     * @param type $content 内容
     * @param type $picurl 图片url
     * @param type $url 跳转url（可不填）
     */
    public function returnNews($object,$title,$content,$picurl,$url = "",$micro=0){
//        print_r($object);
        $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>"
                . "<FromUserName><![CDATA[%s]]></FromUserName>"
                . "<CreateTime>%s</CreateTime>"
                . "<MsgType><![CDATA[news]]></MsgType>"
                . "<ArticleCount>1</ArticleCount>"
                . "<Articles><item><Title><![CDATA[%s]]></Title>"
                . "<Description><![CDATA[%s]]></Description>"
                . "<PicUrl><![CDATA[%s]]></PicUrl>"
                . "<Url><![CDATA[%s]]></Url>"
                . "</item></Articles></xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, 
                $object->ToUserName,time(),$title,$content,$picurl,$url);
        $test = new \Wechat\Model\TestModel();
        $test->create(array('value'=>"News||".$resultStr."||$micro"));
        $test->add();
        echo $resultStr;
    }
    /**
     * 发送绑定信息页面链接
     * @param type $object
     */
    public function returnBindMsg($object){
        $this->returnNews($object, "账户绑定", 
                "若要使用查询功能，需要先绑定校园门户账户", '',
                'http://bbs.scuec.edu.cn/scuecWechat/index.php/wechat/login?key='.$object->FromUserName);
    }
    
    /**
     * 发送课表信息页面链接
     * @param type $object
     */
    public function returnClassMsg($object,$micro = 0){
        $cla = new \Wechat\Model\ClaModel();
        $result = $cla->getCla($object->FromUserName);
        \phpQuery::newDocumentString("<html><body><table>".$result."</table></body></html>");
        $trs = pq('tr');
        $xq = date('N')+1;
        $trnum = 0;
        $z = ($xq-1)==7?"日":($xq-1);
        $optstr = "今天是周".$z."，您的课表信息如下：\n";
        foreach ($trs as $tr) {
            if ($trnum>11)                break;
            $tds = pq($tr)->find('td');
            $num=0;
            foreach ($tds as $td) {
                if (($num == $xq)) {
                    $info =  pq($td)->html();
                    $info = mb_ereg_replace("\n","",$info);
                    $info = mb_ereg_replace("<hr>","\n",$info);
                    $info = mb_ereg_replace(" ","",$info);
                    $info = mb_ereg_replace("&nbsp;","",$info);
                    $info = mb_ereg_replace("　","",$info);
                    
                    $info = strip_tags($info);
                    if (($info!=" ")and(  mb_strlen($info)>2)){
                        $optstr.=$info."\n";
                    }
                }
                $num++;
            }
            $num = 0;
            $trnum++;
        }
        $trnum = 0;
        $xq = ($xq==8)?1:$xq;
        $z = $xq==7?"日":$xq;
        $optstr.=$info."\n明天是周".$z."，您的课表信息如下\n";
        foreach ($trs as $tr) {
            if ($trnum>11)                break;
            $tds = pq($tr)->find('td');
            $num=0;
            foreach ($tds as $td) {
                if (($num == $xq+1)) {
                    $info =  pq($td)->html();
                    $info = mb_ereg_replace("\n","",$info);
                    $info = mb_ereg_replace("<hr>","\n",$info);
                    $info = mb_ereg_replace(" ","",$info);
                    $info = mb_ereg_replace("&nbsp;","",$info);
                    $info = mb_ereg_replace("　","",$info);
                    $info = strip_tags($info);
                    if (($info!=" ")and(  mb_strlen($info)>2)){
                        $optstr.=$info."\n";
                    }
                }
                $num++;
            }
            $num = 0;
            $trnum++;
        }
        $this->returnNews($object, "课表信息", 
        $optstr."点击查看课表详情", '',
                'http://bbs.scuec.edu.cn/scuecWechat/index.php/wechat/class?key='.$object->FromUserName,$micro);
    }
    
    
    /**
     * 回复多条图文消息
     * @param type $object
     * @param type $data
     * @param type $num
     */
    public function returnMultiNews($object,$data,$num){
        $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>"
                . "<FromUserName><![CDATA[%s]]></FromUserName>"
                . "<CreateTime>%s</CreateTime>"
                . "<MsgType><![CDATA[news]]></MsgType>"
                . "<ArticleCount>%s</ArticleCount>"
                . "<Articles>%s</Articles></xml>";
        $items = "";
        for($a = 0;$a<$num;$a++){
            $itemTpl = "<item><Title><![CDATA[%s]]></Title>"
                . "<Description><![CDATA[%s]]></Description>"
                . "<PicUrl><![CDATA[%s]]></PicUrl>"
                . "<Url><![CDATA[%s]]></Url></item>";
            $tmp = sprintf($itemTpl, $data[$a]['title'], $data[$a]['content'], $data[$a]['picurl'], $data[$a]['url']);
            $items .= $tmp;
        }
        $resultStr = sprintf($textTpl, $object->FromUserName, 
                $object->ToUserName,time(),$num,$items);
        $test = new \Wechat\Model\TestModel();
        $test->create(array('value'=>"News||".$resultStr));
        $test->add();
        echo $resultStr;
        
    }
    
    
}
